package com.igeek.collateral.job;

import com.igeek.collateral.constant.RedisImgConstant;
import com.igeek.collateral.utils.QiniuUtils;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.quartz.QuartzJobBean;
import org.springframework.util.CollectionUtils;

import java.util.Set;

/**
 * TODO
 *
 * @author chh
 * @since 2024/7/16
 */
@Slf4j
public class CleanImgJob extends QuartzJobBean {

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        log.info("--------------> 执行删除图片的定时任务....");

        //差集  查询出不在数据库中使用的图片信息
        Set<Object> set = redisTemplate.opsForSet().difference(RedisImgConstant.UPLOAD_IMG, RedisImgConstant.UPLOAD_DB_IMG);
        if(!CollectionUtils.isEmpty(set)){
            for (Object o : set) {
                String img = o.toString();
                //七牛云删除图片
                boolean flag = QiniuUtils.deleteFromQiniu(img);
                if(flag){
                    //Redis中删除图片
                    redisTemplate.opsForSet().remove(RedisImgConstant.UPLOAD_IMG , img);
                    log.info("{} 删除成功" , img);
                }
            }
        }
    }
}
